{% extends "base.html" %}
{% block title %}找回密码 - 安全认证系统{% endblock %}

{% block content %}
<div class="auth-container forgot-bg">
    <div class="layui-container">
        <div class="layui-row">
            <div class="layui-col-md-8 layui-col-lg-6 layui-col-offset-md-2 layui-col-offset-lg-3">
                <div class="auth-card">
                    <div class="auth-header">
                        <h2><i class="fas fa-key"></i> 密码恢复</h2>
                        <p>重置您的账户密码</p>
                    </div>

                    <div class="steps">
                        <div class="step-progress">
                            <div class="step active" data-step="1">
                                <div class="step-icon">1</div>
                                <div class="step-label">验证身份</div>
                            </div>
                            <div class="step" data-step="2">
                                <div class="step-icon">2</div>
                                <div class="step-label">重置密码</div>
                            </div>
                            <div class="step" data-step="3">
                                <div class="step-icon">3</div>
                                <div class="step-label">完成</div>
                            </div>
                        </div>
                    </div>

                    <form class="layui-form auth-form step-content" id="step1">
                        <div class="form-group">
                            <div class="input-with-icon">
                                <i class="fas fa-envelope"></i>
                                <input type="text" name="email" required lay-verify="required|email"
                                    placeholder="请输入注册邮箱地址" autocomplete="off" class="layui-input" id="forget_email">
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="captcha-container">
                                <div class="captcha-input-container">
                                    <div class="input-with-icon">
                                        <i class="fas fa-shield-alt"></i>
                                        <input type="text" name="captcha" required lay-verify="required"
                                            placeholder="请输入验证码" autocomplete="off" class="layui-input"
                                            id="forget_captcha">
                                    </div>
                                </div>
                                <div class="captcha-img-container">
                                    <img src="/captcha" id="captcha-img" class="captcha-img" alt="验证码" title="点击刷新验证码">
                                    <div class="captcha-refresh">点击图片刷新验证码</div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="input-with-icon">
                                <i class="fas fa-check-circle"></i>
                                <input type="text" name="email_captcha" required lay-verify="required"
                                    placeholder="请输入邮箱内获取的验证码" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="form-group">
                            <button class="layui-btn layui-btn-fluid auth-btn" lay-submit lay-filter="step1">
                                <i class="fas fa-arrow-right"></i> 下一步
                            </button>
                        </div>

                        <div class="auth-footer">
                            想起密码了? <a href="/login" class="login-link">返回登录</a>
                        </div>
                    </form>

                    <form class="layui-form auth-form step-content hidden" id="step2">
                        <div class="form-group">
                            <div class="input-with-icon">
                                <i class="fas fa-lock"></i>
                                <input type="password" name="password" id="password" required
                                    lay-verify="required|password" placeholder="设置登录密码（至少8位）" autocomplete="off"
                                    class="layui-input">
                                <i class="fas fa-eye-slash toggle-password" data-target="#password"></i>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="input-with-icon">
                                <i class="fas fa-check-circle"></i>
                                <input type="password" name="confirm" required lay-verify="required|confirmPass"
                                    placeholder="确认登录密码" autocomplete="off" class="layui-input" id="confirm">
                                <i class="fas fa-eye-slash toggle-password" data-target="#confirm"></i>
                            </div>
                        </div>

                        <div class="form-group">
                            <button class="layui-btn layui-btn-fluid auth-btn" lay-submit lay-filter="step2">
                                <i class="fas fa-arrow-right"></i> 下一步
                            </button>
                        </div>

                        <div class="auth-footer">
                            想起密码了? <a href="/login" class="login-link">返回登录</a>
                        </div>
                    </form>

                    <div class="auth-form step-content hidden" id="step3">
                        <div class="success-container">
                            <div class="success-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="success-message">密码重置成功！</div>
                            <p>您的新密码已设置成功，请使用新密码登录系统。</p>
                            <div class="countdown">页面将在 <span id="countdown">5</span> 秒后自动跳转到登录页面</div>

                            <div class="form-group" style="margin-top: 30px;">
                                <button class="layui-btn layui-btn-fluid auth-btn" onclick="location.href='#'">
                                    <i class="fas fa-sign-in-alt"></i> 立即登录
                                </button>
                            </div>
                        </div>
                    </div>


                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script>
    layui.use(['form', 'jquery', 'layer'], function () {
        var form = layui.form;
        var $ = layui.$;
        var layer = layui.layer;

        var userEmail = "";
        var emailFilled = false;
        var flag = 0;


        $('.toggle-password').on('click', function () {
            var $icon = $(this);
            var targetId = $icon.data('target');
            var $input = $(targetId);

            if ($input.attr('type') === 'password') {
                $input.attr('type', 'text');
                $icon.removeClass('fa-eye-slash').addClass('fa-eye');
            } else {
                $input.attr('type', 'password');
                $icon.removeClass('fa-eye').addClass('fa-eye-slash');
            }
        });

        // 自定义表单验证规则
        form.verify({
            email: function (value) {
                if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
                    return '请输入有效的邮箱地址';
                }
            },
            password: function (value) {
                if (value.length < 8) {
                    return '密码长度至少为8个字符';
                }
                if (!/[A-Z]/.test(value)) {
                    return '密码必须包含至少一个大写字母';
                }
                if (!/[a-z]/.test(value)) {
                    return '密码必须包含至少一个小写字母';
                }
                if (!/\d/.test(value)) {
                    return '密码必须包含至少一个数字';
                }
                if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) {
                    return '密码必须包含至少一个特殊字符';
                }
            },
            confirmPass: function (value) {
                if (value !== $('#password').val()) {
                    return '两次输入的密码不一致';
                }
            }
        });


        // 刷新验证码
        $('#captcha-img').click(function () {
            $(this).attr('src', '/captcha?' + Math.random());
        });



        // 监听邮箱输入框是否有内容
        $('#forget_email').on('input', function () {
            userEmail = $(this).val().trim();
            emailFilled = $(this).val().trim() !== '';
        });

        // 监听验证码输入框失去焦点事件
        $('#forget_captcha').on('blur', function () {
            var captchaValue = $(this).val().trim();

            if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(userEmail)) {
                layer.msg('请输入有效的邮箱地址', { icon: 2 });
                return false;
            }

            // 判断邮箱是否已填写，且验证码不为空
            if (emailFilled && captchaValue) {
                var loadIndex = layer.load(2);

                $.ajax({
                    url: '/auth/forgot-password/sent-email',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        "email": userEmail,
                        "captcha": captchaValue,
                        'csrf_token': $('meta[name="csrf-token"]').attr('content'),
                    }),
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.message) {
                            layer.msg(res.message, { icon: 1 });
                            flag = 1;
                        } else {
                            // 刷新验证码
                            $('#captcha-img').attr('src', '/captcha?' + Math.random());
                            layer.msg(res.error || '操作失败', { icon: 2 });
                            flag = 0;
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        var res = xhr.responseJSON;
                        layer.msg(res?.error || '请求错误', { icon: 2 });
                        // 刷新验证码
                        $('#captcha-img').attr('src', '/captcha?' + Math.random());
                        flag = 0;
                    }
                });
                return false;
            }
        });

        form.on('submit(step1)', function (data) {
            if (!flag) {
                layer.msg('请先完成验证码验证', { icon: 2 });
                return false;
            };
            $.ajax({
                url: '/auth/forgot-password/vaildate-email-captcha',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    "email": data.field.email,
                    "captcha": data.field.email_captcha,
                    'csrf_token': $('meta[name="csrf-token"]').attr('content'),
                }),
                success: function (res) {
                    if (res.message) {
                        showStep(2);
                    } else {
                        // 刷新验证码
                        $('#captcha-img').attr('src', '/captcha?' + Math.random());
                        layer.msg(res.error || '操作失败', { icon: 2 });
                    }
                },
                error: function (xhr) {
                    var res = xhr.responseJSON;
                    layer.msg(res ? res.error : '服务器错误', { icon: 2 });
                    // 刷新验证码
                    $('#captcha-img').attr('src', '/captcha?' + Math.random());
                }
            });
            return false;
        });


        form.on('submit(step2)', function (data) {
            $.ajax({
                url: '/auth/forgot-password/set-passwd',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    "email": userEmail,
                    "password": data.field.password,
                    "confirm": data.field.confirm,
                    'csrf_token': $('meta[name="csrf-token"]').attr('content'),
                }),
                success: function (res) {
                    if (res.message) {
                        showStep(3);
                    } else {
                        // 刷新验证码
                        $('#captcha-img').attr('src', '/captcha?' + Math.random());
                        layer.msg(res.error || '操作失败', { icon: 2 });
                    }
                },
                error: function (xhr) {
                    var res = xhr.responseJSON;
                    layer.msg(res ? res.error : '服务器错误', { icon: 2 });
                    // 刷新验证码
                    $('#captcha-img').attr('src', '/captcha?' + Math.random());
                }
            });
            return false;
        });

        // 下一步
        function showStep(stepNumber) {
            $('.step').removeClass('active');
            $(`.step[data-step="${stepNumber}"]`).addClass('active');

            $('.auth-form, .step-content').addClass('hidden');
            $(`#step${stepNumber}`).removeClass('hidden');

            if (stepNumber === 3) {
                startCountdown();
            }
        }

        // 倒计时函数
        function startCountdown() {
            var $countdown = $('#countdown');
            var redirectUrl = '/login'; // 跳转的登录页地址
            var timeLeft = 5;

            $countdown.text(timeLeft);

            var timer = setInterval(function () {
                timeLeft--;
                $countdown.text(timeLeft);

                if (timeLeft <= 0) {
                    clearInterval(timer);
                    window.location.href = redirectUrl;
                }
            }, 1000);
        }

    });
</script>
{% endblock %}